package com.etong.citymap.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.etong.citymap.bean.AssignmentBean;
import com.etong.citymap.bean.HistoryTakeNotesBean;
import com.etong.citymap.bean.ViewHolder;
import com.etong.citymap.db.impl.AppendixDaoImp;
import com.etong.citymap.db.impl.SentenceDaoImp;
import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.module.AppendixBean;
import com.etong.citymap.module.SentenceBean;
import com.etong.citymap.util.DateUtil;
import com.etong.citymap.util.Status;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *
 * 历史记录 保存成功、上传成功
 */
public class HistoryTakeNotesActivity extends Activity implements
		OnClickListener {
	ListView historytn_list;
	ListView historytn_list_t1;
	AlertDialog loadingdialog;
	List<HistoryTakeNotesBean> historyTakeNotesBeans;
	List<HistoryTakeNotesBean> historyTakeNotesBeans1;
	LinearLayout historytn_back;
	LinearLayout historytn_t1;
	LinearLayout historytn_t2;
	UploadReceiver receiver;
	boolean isonload=false;
	private CityApplication cityApplication;
	Calendar calendar=Calendar.getInstance();
	Handler handler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == 2) {
				loadingdialog.dismiss();
				historytn_list.setAdapter(baseAdapter);
				historytn_list_t1.setAdapter(baseAdapter1);
			}
			return false;
		}
	});

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.historytn);
		cityApplication = (CityApplication)getApplication();
		init();
		loadingdialog = new ProgressDialog(this);
		loadingdialog.setTitle(null);
		loadingdialog.setMessage("请稍等,数据加载中...");
		loadingdialog.setCanceledOnTouchOutside(false);
		//loadingdialog.show();
		//new Loading();
		//注册广播接受者
		receiver=new UploadReceiver();
		IntentFilter filter=new IntentFilter("android.intent.action.refresh");
		registerReceiver(receiver, filter);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Intent intent=new Intent("android.intent.action.refresh");
		sendBroadcast(intent);
	}

	void init() {
		historytn_list = (ListView) findViewById(R.id.historytn_list);
		historytn_list_t1 = (ListView) findViewById(R.id.historytn_list_t1);
		historytn_back = (LinearLayout) findViewById(R.id.historytn_back);
		historytn_back.setOnClickListener(this);
		historytn_list.setOnItemClickListener(onItemClickListener);
		historytn_list_t1.setOnItemClickListener(onItemClickListener);
		historytn_t1 = (LinearLayout) findViewById(R.id.historytn_t1);
		historytn_t2 = (LinearLayout) findViewById(R.id.historytn_t2);
		historytn_t2.setOnClickListener(this);
		historytn_t1.setOnClickListener(this);

	}

	class Loading extends Thread {
		public Loading() {
			start();
		}

		@Override
		public void run() {
			   while(!isonload){
				   isonload=true;
					historyTakeNotesBeans = new ArrayList<HistoryTakeNotesBean>();
					historyTakeNotesBeans1 = new ArrayList<HistoryTakeNotesBean>();
					SentenceDaoImp sentenceDaoImp = new SentenceDaoImp(	HistoryTakeNotesActivity.this);
					AppendixDaoImp appendixDaoImp = new AppendixDaoImp(	HistoryTakeNotesActivity.this);
					//find(null, "where superid=?", new String[]{Configure.UserId}, null, null, null, null)
					List<SentenceBean> sentenceBeans = sentenceDaoImp.find();
					String path = Environment.getExternalStorageDirectory()
							+ cityApplication.CameraPath;
					for (SentenceBean bean : sentenceBeans) {
						List<AppendixBean> appendixBeans = appendixDaoImp.find(null,
								"caseid=" + bean.getId(), null, null, null, null, null);
						HistoryTakeNotesBean takeNotesBean = new HistoryTakeNotesBean();
						bean.setAppendixBeans(appendixBeans);
						takeNotesBean.setContent(bean.getSituation());
						takeNotesBean.setTitle("");
						takeNotesBean.setId(bean.getId());
						takeNotesBean.setCreatedate(bean.getCreatedate());
						takeNotesBean.setBean(bean);
					    
						//删除代码注释
						if(isdelete(bean.getCreatedate())){
							sentenceDaoImp.delete(bean.getId());
							for(AppendixBean appendixBean:appendixBeans){
								File file=new File(path + "/"+ appendixBean.getPath());
								file.delete();
								sentenceDaoImp.delete((int)appendixBean.getId());
							}
							//break;
						}
						if (appendixBeans.size() > 0) {
							takeNotesBean.setIcon(BitmapFactory.decodeFile(path + "/"
									+ appendixBeans.get(0).getPath()));
						}
						if (bean.getSaveState() == Status.SaveState_t1&&bean.getSuperid().equals(cityApplication.getUserId())) {
							historyTakeNotesBeans.add(takeNotesBean);
						} else if (bean.getSaveState() == Status.SaveState_t2&&bean.getSuperid().equals(cityApplication.getUserId())) {
							historyTakeNotesBeans1.add(takeNotesBean);
						}

					}
					handler.sendEmptyMessage(2);
			   }
			   isonload=false;
				
			  
			   
				
				
			
			
		}
	}

	boolean isdelete(Date createdate){
		Date temp = DateUtil.addDay(new Date(), -1*cityApplication.getHistorySaveTime());
		if(temp.after(createdate))
			return true;
		else 
			return false;
		/*int year=calendar.get(Calendar.YEAR);
		int month=calendar.get(Calendar.MONTH)+1;
		int day=calendar.get(Calendar.DATE);
		String date=year+":"+createdate;
		try{
		Date create=DateUtil.setStringToDate("YYYY:MM:DD HH:mm", date);
		int cmonth=create.getMonth();
		int cday=create.getDay();
		if(month>cmonth){
			int jg=((day*30)-Configure.HistorySaveTime)-cday;
			if(jg==0){
				return true;
			}
			
		}else{
			int jg=(day-Configure.HistorySaveTime)-cday;
			if(jg==0){
				return true;
			}
		}
		}catch(Exception e){LogUtil.e(e);}
		
		
		return false;*/
	}
	public BaseAdapter baseAdapter = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			ViewHolder vHolder;
			if (convertView == null) {
				convertView = LayoutInflater
						.from(HistoryTakeNotesActivity.this).inflate(
								R.layout.listitem, null);
				ImageView icon = (ImageView) convertView
						.findViewById(R.id.listitem_icon);
				ImageView icon_top = (ImageView) convertView
						.findViewById(R.id.listitem_icon_top);
				TextView title = (TextView) convertView
						.findViewById(R.id.listitem_title);
				TextView date = (TextView) convertView
						.findViewById(R.id.listitem_date);
				TextView content = (TextView) convertView
						.findViewById(R.id.listitem_content);
				vHolder = new ViewHolder();
				vHolder.setContent(content);
				vHolder.setDate(date);
				vHolder.setTitle(title);
				vHolder.setIcon(icon);
				convertView.setTag(vHolder);
			} else {
				vHolder = (ViewHolder) convertView.getTag();
			}
			if (historyTakeNotesBeans != null) {
				HistoryTakeNotesBean notesBean = historyTakeNotesBeans
						.get(position);
				StringBuffer text=new StringBuffer();
				if(notesBean.getBean()!=null){
					int flag=notesBean.getBean().getFlag();
					if(flag==Status.ProjectType_HC){
						text.append("(核查)");
					}else if(flag==Status.ProjectType_HS){
						text.append("(核实)");
					}else if(flag==Status.ProjectType_SB){
						text.append("(上报)");
					}
					int upstatue=notesBean.getBean().getUploadState();
					text.append(Status.uploadErorr.get(upstatue));
					int c = Color.rgb(60,140,250);
					if(upstatue>=0)
						c = Color.rgb(12,160,0);
					else if(upstatue<=-1000)
						c = Color.rgb(200,0,0);
					vHolder.getTitle().setTextColor(c);
					/*if(upstatue==0){
						text.append("数据正在上传");
					}else if(upstatue==1){
						 text.append("数据不合法");
						 vHolder.getTitle().setTextColor(Color.RED);
					}else if(upstatue==2){
						text.append("网络连接不稳定");
						vHolder.getTitle().setTextColor(Color.RED);
					}else if(upstatue==3){
						text.append("服务器错误");
						vHolder.getTitle().setTextColor(Color.RED);
					}*/
					
				}
				
				vHolder.getTitle().setText(text.toString());
				Date date = notesBean.getCreatedate();
				vHolder.getDate().setText(DateUtil.setSimpleDateFormat(date, "MM-dd HH:mm"));
				vHolder.getContent().setText(notesBean.getContent());
				if (notesBean.getIcon() != null) {
					vHolder.getIcon().setImageBitmap(notesBean.getIcon());
				}
			}
			return convertView;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public int getCount() {
			if (historyTakeNotesBeans != null) {
				return historyTakeNotesBeans.size();
			}
			return 0;
		}
	};

	public BaseAdapter baseAdapter1 = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			ViewHolder vHolder;
			if (convertView == null) {
				convertView = LayoutInflater
						.from(HistoryTakeNotesActivity.this).inflate(
								R.layout.listitem, null);
				ImageView icon = (ImageView) convertView
						.findViewById(R.id.listitem_icon);
				ImageView icon_top = (ImageView) convertView
						.findViewById(R.id.listitem_icon_top);
				TextView title = (TextView) convertView
						.findViewById(R.id.listitem_title);
				TextView date = (TextView) convertView
						.findViewById(R.id.listitem_date);
				TextView content = (TextView) convertView
						.findViewById(R.id.listitem_content);
				vHolder = new ViewHolder();
				vHolder.setContent(content);
				vHolder.setDate(date);
				vHolder.setTitle(title);
				vHolder.setIcon(icon);
				convertView.setTag(vHolder);
			} else {
				vHolder = (ViewHolder) convertView.getTag();
			}
			if (historyTakeNotesBeans1 != null) {
				HistoryTakeNotesBean notesBean = historyTakeNotesBeans1
						.get(position);
				String text="";
				
				if(notesBean.getBean().getFlag()==Status.ProjectType_HC){
					text="(已核查)";
				}else if(notesBean.getBean().getFlag()==Status.ProjectType_HS){
					text="(已核实)";
				}else if(notesBean.getBean().getFlag()==Status.ProjectType_SB){
					text="(已上报)";
				}
				vHolder.getTitle().setText(text);
				String date = DateUtil.setSimpleDateFormat(notesBean.getCreatedate(), "MM-dd HH:mm");
				vHolder.getDate().setText(date);
				vHolder.getContent().setText(notesBean.getContent());
				if (notesBean.getIcon() != null) {
					vHolder.getIcon().setImageBitmap(notesBean.getIcon());
				}
			}
			return convertView;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public int getCount() {
			if (historyTakeNotesBeans1 != null) {
				return historyTakeNotesBeans1.size();
			}
			return 0;
		}
	};

	@Override
	public void onClick(View v) {
		if (historytn_back == v) {
			unregisterReceiver(receiver);
			Log.i("System.out.p", "解除绑定");
			finish();
		}
		if (historytn_t2 == v) {
			historytn_t2.setBackgroundResource(R.drawable.mytypeback_down);
			historytn_t1.setBackgroundResource(R.drawable.mytypeback);
			historytn_list.setVisibility(LinearLayout.GONE);
			historytn_list_t1.setVisibility(LinearLayout.VISIBLE);
			Intent intent=new Intent("android.intent.action.refresh");
			sendBroadcast(intent);
		}
		if (historytn_t1 == v) {
			historytn_t1.setBackgroundResource(R.drawable.mytypeback_down);
			historytn_t2.setBackgroundResource(R.drawable.mytypeback);
			historytn_list.setVisibility(LinearLayout.VISIBLE);
			historytn_list_t1.setVisibility(LinearLayout.GONE);
			Intent intent=new Intent("android.intent.action.refresh");
			sendBroadcast(intent);
		}

	}

	public OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int persion,
				long arg3) {
			cityApplication.setImageList(null);
			//Configure.ImageList=null;
			if (arg0 == historytn_list) {
				SentenceBean bean=historyTakeNotesBeans.get(persion).getBean();
				cityApplication.setCacheSentence(bean);
				//Configure.CacheSentence=bean;
				AssignmentBean assignmentBean=new AssignmentBean();
				assignmentBean.setBigclass(bean.getBigclass());
				assignmentBean.setType(bean.getEventtype());
				assignmentBean.setSmallclass(bean.getSmallclass());
				assignmentBean.setX(bean.getXcoor());
				assignmentBean.setY(bean.getYcoor());
				assignmentBean.setSituation(bean.getSituation());
				Intent intent=new Intent(HistoryTakeNotesActivity.this, ProblemUploadActivity.class);
				intent.putExtra("bean", assignmentBean);
				intent.putExtra("historytype", Status.SaveState_t2);
				startActivity(intent);
			}
			if (arg0 == historytn_list_t1) {
				SentenceBean bean=historyTakeNotesBeans1.get(persion).getBean();
				//Configure.CacheSentence=bean;
				cityApplication.setCacheSentence(bean);
				AssignmentBean assignmentBean=new AssignmentBean();
				assignmentBean.setBigclass(bean.getBigclass());
				assignmentBean.setType(bean.getEventtype());
				assignmentBean.setSmallclass(bean.getSmallclass());
				assignmentBean.setX(bean.getXcoor());
				assignmentBean.setY(bean.getYcoor());
				assignmentBean.setSituation(bean.getSituation());
				Intent intent=new Intent(HistoryTakeNotesActivity.this, ProblemUploadActivity.class);
				intent.putExtra("bean", assignmentBean);
				intent.putExtra("historytype", Status.SaveState_t1);
				startActivity(intent);
			}
		}
	};
	
	//更新历史记录的广播接收者
	public class UploadReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			Log.i("System.out.p", "开始更新");
			loadingdialog.show();
			if(!isonload){
				new Loading();
			}                  
		}
		
	}
}
